package com.scenic.map.service;

import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class MapService {
    private static final String API_KEY = "770e1be9dd8196f7877303dd3a0d49a5";
    private final RestTemplate restTemplate = new RestTemplate();

    // 地名转坐标
    private String geocode(String address) {
        String url = "https://restapi.amap.com/v3/geocode/geo?address=" + address + "&key=" + API_KEY;
        String resp = restTemplate.getForObject(url, String.class);
        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode root = mapper.readTree(resp);
            JsonNode geocodes = root.path("geocodes");
            if (geocodes.isArray() && geocodes.size() > 0) {
                String location = geocodes.get(0).path("location").asText();
                if (StringUtils.hasText(location)) {
                    return location;
                }
            }
            // 打印高德API原始响应，便于排查
            System.err.println("高德地理编码API响应: " + resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String planRoute(String origin, String destination) {
        String originBak = origin;
        String destinationBak = destination;
        // 如果不是经纬度，先转为经纬度
        if (!origin.matches("^-?\\d+\\.\\d+,-?\\d+\\.\\d+$")) {
            String geo = geocode(origin);
            if (StringUtils.hasText(geo)) origin = geo;
            else return String.format("{\"error\":\"起点[%s]无法获取坐标，请输入更详细的地名或直接传经纬度\"}", originBak);
        }
        if (!destination.matches("^-?\\d+\\.\\d+,-?\\d+\\.\\d+$")) {
            String geo = geocode(destination);
            if (StringUtils.hasText(geo)) destination = geo;
            else return String.format("{\"error\":\"终点[%s]无法获取坐标，请输入更详细的地名或直接传经纬度\"}", destinationBak);
        }
        String url = "https://restapi.amap.com/v3/direction/driving?origin=" + origin +
                "&destination=" + destination + "&key=" + API_KEY;
        return restTemplate.getForObject(url, String.class);
    }
} 